package com.yijiankang.threaddemo.controller;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * @author Mr
 * @title: ConcurrentTest
 * @projectName mytest
 * @description: TODO
 * @date 2019/7/1611:17
 */
@Slf4j
public class ConcurrentTest {

    //请求总数
    private static int clientTotal = 5000;

    //并发数
    private static int threadTotal = 200;

    private static int count = 0;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for(int i=0;i<clientTotal;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.error("exceprion",e);
                }
                countDownLatch.countDown();
            });

        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("1111111111"+count);
        log.info("count:{}",count);
    }

    //加入syschronized   同一时间只能有一个线程 访问此方法
    private synchronized static void add(){
        count++;
    }


}
